﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Xml.Linq;
using System.Threading;
using System.Globalization;
using Nivdal.AuxCode;

namespace Nivdal
{
    public partial class MatchPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Title = Resources.Resource.Default_PageTitle + ", " + Resources.Resource.MatchPage_PageTitle;
            //if (!HttpContext.Current.User.Identity.IsAuthenticated)
            //    Response.Redirect("~/Default.aspx");
            
            OnlineUser ou = (OnlineUser)Session["User"];
   
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            //this.Title = Resources.Resource.MatchPage_Title + " - " + GND.ReturnAppTitle();

            //if (ou.TeamId == "Null")
            //    Response.Redirect("~/GeneralMessage.aspx?MessageString=M74ggdizz5wfeh");
            
            if (Request.QueryString["ConfirmNote"] != null)
            {
                this.Message.ForeColor = System.Drawing.Color.Green;
                this.Message.Text = Request.QueryString["ConfirmNote"].ToString();
            }

            string MatchId = null;
            string MatchStage = null;
            int IntMatchStage = -1;

            if (Request.QueryString["MatchId"] != null)
            {
                MatchId = Request.QueryString["MatchId"];
                this.MatchIdHiddenField.Value = MatchId;
            }

            if (MatchId == null)
                Response.Redirect("GeneralMessage.aspx?MessageString=l43ZZOTLOB");
            
            this.StadiumAssignmentPanel.Visible = IsStadiumAsignment();

            MatchStage = MatchStageValue(MatchId);
            IntMatchStage = Convert.ToInt16(MatchStage);

            if (IntMatchStage >= 2)
            {
                this.MatchRatingButton.Visible = true;
                this.MatchRatingButton.NavigateUrl = "MatchRatings.aspx?MatchId=" + MatchId;
            }
            
            bool IsNT = GND.ReadNivdalBoolData("MatchId", "Nivdal_IsMatchNT", MatchId);

            if (IsNT)
                IsNationalTeamHiddenField.Value = "true";
            else
                IsNationalTeamHiddenField.Value = "false";
            
            if ((IntMatchStage > 3) || (IntMatchStage < 0)) //Not legal MatchStage
                Response.Redirect("GeneralMessage.aspx?MessageString=l43ATUOTLOB");
            else
            {
                //if (IsPostBack)
                //{
                //    this.ScoreBordSqlDataSource.SelectParameters.Clear();
                //    this.HomeTeamGoalsAndWarningsForScoreboardSqlDataSource.SelectParameters.Clear();
                //    this.AwayTeamGoalsAndWarningsForScoreboardSqlDataSource.SelectParameters.Clear();
                //    this.MatchEventsSqlDataSource.SelectParameters.Clear();
                //    this.ShowStadiumsValuesSqlDataSource.SelectParameters.Clear();
                //}
                if (!IsPostBack)
                {
                    this.ScoreBordSqlDataSource.SelectParameters.Add("MatchId", MatchId);
                    this.ScoreBordSqlDataSource.SelectParameters.Add("Language", ou.Language);
                    this.HomeTeamGoalsAndWarningsForScoreboardSqlDataSource.SelectParameters.Add("MatchId", MatchId);
                    this.HomeTeamGoalsAndWarningsForScoreboardSqlDataSource.SelectParameters.Add("Language", ou.Language);
                    this.AwayTeamGoalsAndWarningsForScoreboardSqlDataSource.SelectParameters.Add("MatchId", MatchId);
                    this.AwayTeamGoalsAndWarningsForScoreboardSqlDataSource.SelectParameters.Add("Language", ou.Language);
                    //this.SubstitutionsForScoreboardSqlDataSource.SelectParameters.Add("MatchId", MatchId);
                    this.MatchEventsSqlDataSource.SelectParameters.Add("MatchId", MatchId);
                    this.MatchEventsSqlDataSource.SelectParameters.Add("Language", ou.Language);
                    this.MatchEventsSqlDataSource.SelectParameters.Add("UserId", ou.UserId);
                    //this.MatchEventsSqlDataSource.SelectParameters.Add("Direction", "1");
                    //this.MatchEventsSqlDataSource.SelectParameters.Add("Direction", "0");
                    
                    this.ShowStadiumsValuesSqlDataSource.SelectParameters.Add("UserId", ou.UserId);
                    this.ShowStadiumsValuesSqlDataSource.SelectParameters.Add("IsNT", IsNT ? "1" : "0"); 
                    this.StadiumsCostSQLDataSourse.SelectParameters.Add("UserId", ou.UserId);
                    this.StadiumsCostSQLDataSourse.SelectParameters.Add("IsNT", IsNT ? "1" : "0");

                }
                MatchOrdersAssignmentStatus.Value = GND.ReadNivdalIntData("MatchId", "UserId", "Nivdal_GetMatchOrdersAssignmentStatus", MatchId, ou.UserId);
                //this.Message.Text = GND.ReadNivdalBoolData("@UserId", "@MatchId", "Nivdal_ShouldUserGiveInstructionsToMatch", ReurnUserId(), ReurnMatchId()).ToString();

            }
            //this.ShowingSummaryLabel.Visible = (this.MatchEventsGridView.Rows.Count > 0);
            //this.ShowingSummaryLabel.Visible = (this.MatchEventsRepeater.Items.Count > 0);

            string MatchTitle = GND.ReadNivdalStringData("@MatchId", "Nivdal_GetMatchTitleString", MatchId);
            this.PageNameLabel.Text = MatchTitle + " " + Resources.Resource.MatchPage_PageNameLabel;
        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                this.ScoreBordListView.DataBind();
                //this.MatchEventsRepeater.DataBind();
                //this.MatchEventsGridView.DataBind();
                NewMatchEventsRepeater.DataBind();
                this.AwayTeamGoalsAndWarningsForScoreboardSqlDataSource.DataBind();
                this.HomeTeamGoalsAndWarningsForScoreboardSqlDataSource.DataBind();
            }
            finally { }

        }

        protected string MatchStageValue(string MatchId)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            string MS = "";
            MS = (GND.ReadNivdalIntData("@MatchId", "Nivdal_GetMatchStage", MatchId));
            return MS;
        }

        protected void BookmarkLinkButton_Click(Object sender, EventArgs e)
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            BookMarkTheMatch(ou.UserId, MatchIdHiddenField.Value);
            //this.Message.Text = (ReurnUserId().ToString() + " " + ReurnMatchId().ToString() + " ");
        }

        protected void BookMarkTheMatch(string UserId, string MatchId)
        {

            string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            System.Data.IDbConnection dbConnection = new System.Data.SqlClient.SqlConnection(conn);
            System.Data.IDbCommand dbCommand = new System.Data.SqlClient.SqlCommand();
            dbCommand.CommandText = "Nivdal_BookmarkMatch";
            dbCommand.CommandType = CommandType.StoredProcedure;
            dbCommand.Connection = dbConnection;

            SqlParameter dbParam_UserId = new SqlParameter();
            dbParam_UserId.ParameterName = "@UserId";
            dbParam_UserId.Value = UserId;
            dbParam_UserId.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_UserId);

            SqlParameter dbParam_BookmarkedMatch = new SqlParameter();
            dbParam_BookmarkedMatch.ParameterName = "@BookmarkedMatch";
            dbParam_BookmarkedMatch.Value = MatchId;
            dbParam_BookmarkedMatch.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_BookmarkedMatch);

            SqlParameter dbParam_Answer = new SqlParameter();
            dbParam_Answer.ParameterName = "@Answer";
            dbParam_Answer.Value = "";
            dbParam_Answer.DbType = DbType.String;
            dbParam_Answer.Direction = ParameterDirection.Output;
            dbParam_Answer.Size = 64;
            dbCommand.Parameters.Add(dbParam_Answer);

            try
            {

                dbConnection.Open();
                dbCommand.ExecuteScalar();
                Response.Redirect("Bookmarks.aspx?ConfirmNote=" + dbParam_Answer.Value.ToString());
            }
            catch (Exception SQLDBException)
            {
                this.Message.Text = Convert.ToString(SQLDBException);
            }

            finally
            {
                dbConnection.Close();
            }

        }

        protected bool IsStadiumAsignment()
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            return (GND.ReadNivdalBoolData("@UserId", "@MatchId", "Nivdal_ShouldUserAssignStadiumToMatch", ou.UserId, MatchIdHiddenField.Value));
            //return true;

        }

        protected void AssignStadiumButton_Click(object sender, EventArgs e)
        {
            //this.Message.Text = "lolo";
            AssignTheStadium(StadiumsDropDownList.SelectedItem.Value, MatchIdHiddenField.Value);
        }

        protected void AssignTheStadium(string StadiumId, string MatchId)
        {
            string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            System.Data.IDbConnection dbConnection = new System.Data.SqlClient.SqlConnection(conn);
            System.Data.IDbCommand dbCommand = new System.Data.SqlClient.SqlCommand();
            dbCommand.CommandText = "Nivdal_StadiumAssignStadiumToMatch";
            dbCommand.CommandType = CommandType.StoredProcedure;
            dbCommand.Connection = dbConnection;

            SqlParameter dbParam_MatchId = new SqlParameter();
            dbParam_MatchId.ParameterName = "@MatchId";
            dbParam_MatchId.Value = MatchId;
            dbParam_MatchId.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_MatchId);

            SqlParameter dbParam_StadiumId = new SqlParameter();
            dbParam_StadiumId.ParameterName = "@StadiumId";
            dbParam_StadiumId.Value = StadiumId;
            dbParam_StadiumId.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_StadiumId);

            SqlParameter dbParam_Answer = new SqlParameter();
            dbParam_Answer.ParameterName = "@Answer";
            dbParam_Answer.Value = "";
            dbParam_Answer.DbType = DbType.String;
            dbParam_Answer.Direction = ParameterDirection.Output;
            dbParam_Answer.Size = 64;
            dbCommand.Parameters.Add(dbParam_Answer);

            try
            {

                dbConnection.Open();
                dbCommand.ExecuteScalar();
                string NT = (IsNationalTeamHiddenField.Value == "true") ? "&NationalTeam=yes" : "";
                Response.Redirect("ListOfTeamMatches.aspx?ConfirmNote=" + dbParam_Answer.Value.ToString() + NT);
            }
            catch (Exception SQLDBException)
            {
                this.Message.Text = Convert.ToString(SQLDBException);
            }

            finally
            {
                dbConnection.Close();
            }
        }

        //protected string GetIconByMatchType(object o)
        //{
        //    string ReturnValue = "~/Images/Icons/";
        //    string Type = o.ToString();

        //    switch (Type)
        //    {
        //        case "1":
        //            ReturnValue += "LeagueIcon.png";
        //            break;
        //        case "2":
        //            ReturnValue += "NationalCupIcon.png";
        //            break;
        //        case "3":
        //            ReturnValue += "InternationalCupIcon.png";
        //            break;
        //        default:
        //            ReturnValue += "FriendlyIcon.png";
        //            break;
        //    }
        //    return (ReturnValue);
        //}

        protected void AddMatchToLive(object sender, EventArgs e)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            GND.ExecNivdalSQL("MatchId", "UserId", "Nivdal_LiveAddMatchToLive", MatchIdHiddenField.Value, ou.UserId);
            Response.Redirect("Live.aspx");
        }

        protected override void InitializeCulture()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(ou.UICulture);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ou.Culture);
        }

        protected string FormatNumber(object num)
        {
            string returnValue;

            try
            {
                returnValue = int.Parse(num.ToString()).ToString("N0");
            }
            catch
            {
                returnValue = num.ToString();
            }
            return returnValue;
        }

        protected bool IsPremium()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            return ou.IsPremium;
        }


        public bool IsAllowedLive(Object CanAddToLive)
        {
            GlobalFunctions GF = new GlobalFunctions();
            return GF.IsAllowedLive(CanAddToLive);
        }

        protected string MatchInstructionsPageAddress()
        {
            string MatchId = this.MatchIdHiddenField.Value;
            return ("~/MatchInstructions_New.aspx?MatchId=" + MatchId);
        }

        protected string MatchInstructionsPageImage()
        {
            string ImageFileName = MatchOrdersAssignmentStatus.Value;
            if (ImageFileName == "1")
                return ("~/Images/Icons/add Instructions.gif");
            if (ImageFileName == "2")
                return ("~/Images/Icons/edit Instructions.png");
            return ("");
        }

        protected string MatchInstructionsPageToolTip()
        {
            string ImageFileName = MatchOrdersAssignmentStatus.Value;
            if (ImageFileName == "1")
                return (Resources.Resource.MatchPage_AssignInstructions);
            if (ImageFileName == "2")
                return (Resources.Resource.MatchPage_EditInstructions);
            return ("");
        }

        protected bool MatchInstructionsLinkVisible()
        {
            string ImageFileName = MatchOrdersAssignmentStatus.Value;
            if ((ImageFileName == "2") || (ImageFileName == "1"))
                return (true);
            return (false);
        }

        protected string ShowNewMatchSlideScriptText(object EventId)
        { 
            string ReturnValue = "<script type=\"text/javascript\" language=\"javascript\">";
            ReturnValue += "ShowNewMatchEvent(\"event" + EventId.ToString() + "\");";
            ReturnValue += "</script>";

            return ReturnValue;
        }
    }
}